﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Net;
using System.IO;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace RMS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            txtSerialNumber.Text = ProcessorID();
            string unique = ProcessorID();
            txtKey.Text =  GetLicenseInfo(string.Format("http://ec2-54-251-5-113.ap-southeast-1.compute.amazonaws.com:8080/license/services/restService/key?uniqueID={0}&startDate=1337241696593&duration=1", unique));
        }

       

        private string ProcessorID()
        {            
            ManagementObjectCollection mbsList = null;
            ManagementObjectSearcher mbs = new ManagementObjectSearcher("Select * From Win32_processor");
            mbsList = mbs.Get();
            string id = "";
            foreach (ManagementObject mo in mbsList)
            {
                id = mo["ProcessorID"].ToString();
            }

            return id;
        }

        private string GetLicenseInfo(string url)
        {
            var request = WebRequest.Create(url);
            string stringJson;
            var response = (HttpWebResponse)request.GetResponse();

            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                stringJson = sr.ReadToEnd();
            }

            XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(stringJson);
            
            return doc.ChildNodes[0].InnerText;

            
        }

        //private string CheckLicense()
        //{
        //    JObject o = new JObject(
        //              new JProperty("Name", "John Smith"),
        //              new JProperty("BirthDate", new DateTime(1983, 3, 20))
        //              );

        //    JsonSerializer serializer = new JsonSerializer();
        //    LicenseInfo p = (LicenseInfo)serializer.Deserialize(new JTokenReader(o), typeof(LicenseInfo));

        //    Console.WriteLine(p.Name);
        //}
    }

    public class LicenseInfo
    {
        public DateTime LicenseStartDate { get; set; }
        public DateTime LicenseExpireDate { get; set; }
        public string LicenseKey { get; set; }
        public string UniqueString { get; set; }

    }
}
